package uc.org.jkas.app;
import java.util.HashMap;
import uc.org.jkas.model.ApplicationsM;
import uc.org.jkas.model.MembersM;
import uc.org.jkas.model.MemberlogsM;
public class Api extends ApiBase
{   boolean valid=false;
    ApplicationsM am = new ApplicationsM();
	MembersM members = new MembersM();
    String appid="";
	public void index()
	{echo("successful");
	}
	public boolean init()
	{boolean res=false;
		
		if(IS_POST())
		{
	     this.appid=P("appid");
         String authkey=P("authkey");
		 String sign=P("sign");
		 HashMap<String,String> applications = am.getInfo(this.appid);
		 String authkey2 = applications.get("authkey");
		 String allowips = applications.get("allowips");
		 boolean is_verify=applications.get("keysverify").equals("1");
		 if(authkey.equals(authkey2)) {
			  valid = true;
			  if(allowips!=null && !allowips.equals("") && !allowips.contains(clientIp())) {
				 valid = false;
			  }
			  
		 }

		if(valid && is_verify)
			{HashMap<String,String> params=P();
		      params.remove("sign");
              valid=verify(mapsorturl(params),sign, applications.get("pubkey"));
			}
            
		  res=true;
		}
		else
		{res=false;
			echo("{\"code\":-4,\"msg\":\"illegal\"}");
		}
		return res;
	}

	public void login()
	{  
	   String res="{}";
	   if(valid)
		{
			String username = P("username");
	        String password = P("password");
	        int ip = ip2int(P("ip"));
			HashMap<String,Object> params=new HashMap<String,Object>();
	        HashMap<String,String> user=members.getByName(username);
			if(!user.isEmpty()) {
			   if(0==toInt(user.get("status")))
				{res = "{\"code\":0,\"msg\":\"deny login\"}";//用户禁用
				}
				else
				{
				if(user.get("password").equals(members.encodePassword(password,user.get("salt")))) {
					params.put("lastlogintime",time());
		            params.put("lastloginip",ip);
			        members.update(strc("uid=",user.get("uid")),params);
			        HashMap<String,Object> r=new HashMap<String,Object>();
			        user.remove("password");
			        user.remove("salt");
					user.put("code","1");
					user.put("msg","success");
					user.put("user_id",user.get("uid"));
					user.put("user_name",user.get("username"));
			        res=jsonStr(user);
					MemberlogsM mlm=new MemberlogsM();
					HashMap<String,Object> data=new HashMap<String,Object>();
					data.put("uid",user.get("uid"));
					data.put("login_time",time());
					data.put("login_ip",ip);
					data.put("appid",this.appid);
					mlm.insert(data);
				} else {
		            res="{\"code\":7,\"msg\":\"wrong password\"}";//密码错误
				}
			  }//用户禁用
			} else {
				res="{\"code\":2,\"msg\":\"username don't exists\"}";//用户不存在
			}
		} else {
			res = "{\"code\":-4,\"msg\":\"illegal\"}";//非法
		}
	    echo(res);
	}
	
	public void register(){
		String res="{}";
		if(valid) {
			String username = P("username");
		    String password = P("password");
		    String mobile = P("mobile");
			int country = Pint("country");
		    String email = P("email");
		    int ip = ip2int(P("ip"));
		    HashMap<String,String> info=new HashMap<String,String>();
		     info=members.getByName(username);
            if(info==null || info.isEmpty()) {
				boolean is_ok = true;
				if(mobile!=null && mobile.equals("")==false) {
					if(valid().checkMobile(mobile,country)) {
						info=members.getByMobile(mobile);
						if(info!=null && !info.isEmpty()) {
							is_ok=false;
				            res="{\"code\":3,\"msg\":\"mobile exists\"}";//手机号已经存在了
						}
					} else {
						is_ok=false;
					    res="{\"code\":5,\"msg\":\"wrong mobile\"}";//手机号码格式不正确
					}
				}
				
				if(is_ok && email!=null && email.equals("")==false ) {
					if(valid().checkEmail(email)) {
			           info=members.getByEmail(email);
				       if(info!=null && !info.isEmpty()) {
						  is_ok=false;
				          res="{\"code\":4,\"msg\":\"email exists\"}";//邮件已经存在了
					   }
					} else {
					   is_ok=false;
					   res="{\"code\":6,\"msg\":\"wrong email\"}";//邮件格式不正确
					}
				}
				
				if(is_ok) {
	                HashMap<Integer,Object> data=new HashMap<Integer,Object>();
                    int salt=random(100000,999999);
                    data.put(1,username);
		            data.put(2,members.encodePassword(password,String.valueOf(salt)));
		            data.put(3,mobile);
		            data.put(4,email);
		            data.put(5,ip);
		            data.put(6,time());
		            data.put(7,salt);
					data.put(8,this.appid);
	                int nuid=members.fields("username,password,mobile,email,regip,regdate,salt,appid").values("?,?,?,?,?,?,?,?").prepareInsert(data);
		            if(nuid>0) {
						res=strc("{\"code\":1,\"msg\":\"success\",\"uid\":",nuid,",\"user_id\":",nuid,"}");//注册成功
		            } else {
						res="{\"code\":-2,\"msg\":\"failed\"}";//注册失败
		            }
               }
				
			} else {
				res="{\"code\":2,\"msg\":\"username exists\"}";//用户名存在了
			}		
		} else {
			res = "{\"code\":-4,\"msg\":\"illegal\"}";//非法
		}
		echo(res);
	}
	
	public void modify() {
		String res="{}";
		
		if(valid) {
			String username = P("username");
			String newusername = P("newusername");
			String password = P("password");
			String mobile = P("mobile");
			int country = Pint("country");
			String email = P("email");
			String oldpassword = P("oldpassword");
			String forcestr = P("force");//force为true时，强制修改，不用校验旧密码
			boolean force = Boolean.valueOf(forcestr).booleanValue();
			HashMap<Integer,Object> params=new HashMap<Integer,Object>();
		    HashMap<String,String> user=members.getByName(username);
			HashMap<String,String> info=null;
		    boolean is_ok=true;
		    String uid="";
		    StringBuilder sb=new StringBuilder();
			if(user==null || user.isEmpty()) {
				is_ok=false;
		        res="{\"code\":2,\"msg\":\"username not found\"}";//用户名找不到
			}

			if(is_ok && newusername!=null && newusername.equals("")==false && newusername.equals(username)==false)
			{if(members.validUserName(newusername))
					{  info=members.getByName(newusername);
			           if(info!=null && info.isEmpty()==false)
				        {is_ok=false;
			             res="{\"code\":2,\"msg\":\"username exists\"}";//用户名存在了
				        }
				         else
				          {sb.append("username='").append(newusername).append("'");
				          }
					}
					else
					{  is_ok=false;
						res="{\"code\":-1,\"msg\":\"invalid username\"}";//用户名无效
					}
				
			}
			
			if(is_ok && mobile!=null && mobile.equals("")==false && mobile.equals(user.get("mobile"))==false) {     
				if(valid().checkMobile(mobile,country)) {
			           info=members.getByMobile(mobile);
						if(info!=null && !info.isEmpty()) {
						   is_ok=false;
				           res="{\"code\":3,\"msg\":\"mobile exists\"}";//手机号已经存在
					    } else {
							if(sb.length()>0)
							{sb.append(",");
							}
						   sb.append("mobile='").append(mobile).append("'");
						}
				} else {
					is_ok=false;
					res="{\"code\":5,\"msg\":\"wrong mobile\"}";//手机号码格式不正确
				}
			}
			
			if(is_ok && email!=null && email.equals("")==false && email.equals(user.get("email"))==false)
			{     
				if(valid().checkEmail(email))
					{
			           info=members.getByEmail(email);
						if(info!=null && !info.isEmpty()) 
					    {is_ok=false;
				         res="{\"code\":3,\"msg\":\"email exists\"}";//邮件地址已经存在
					    }
						else
						{   if(sb.length()>0)
							{sb.append(",");
							}
							sb.append("email='").append(email).append("'");
						}
					}
					else
					{is_ok=false;
					 res="{\"code\":6,\"msg\":\"wrong email\"}";//邮件格式不正确
					}
			}
			
			if(is_ok && !force)
			{if(user.get("password").equals(members.encodePassword(oldpassword,user.get("salt")))==false)
				{is_ok=false;
				 res="{\"code\":8,\"msg\":\"wrong old password\"}";//输入的旧密码不正确
				}
			}
			
			if(is_ok)
			{ if(oldpassword.equals(password)==false)
				{ String salt=String.valueOf(random(100000,999999));
			              if(sb.length()>0)
							{sb.append(",");
							}
				  sb.append("password='").append(members.encodePassword(password,salt)).append("'");
				  sb.append(",salt='").append(salt).append("'");
				}

				int n=members.set(sb.toString()).where("username='"+username+"'").update();
				if(n>0)
				{res="{\"code\":1,\"msg\":\"success\"}";//变更成功
				}
				else
				{res="{\"code\":-2,\"msg\":\"failed\"}";//变更失败
				}
				sb=null;
			}
			
		} else {
			res = "{\"code\":-4,\"msg\":\"illegal\"}";//非法
		}
		
        echo(res);
	}
	
	public void check() {
	   String res="{}";
	   if(valid) {
			String value=P("value");
			String column=P("column");
			int country=Pint("country");		
			if(column!=null && value!=null && value.equals("")==false)
			{
			String uid="";
			HashMap<Integer,Object> params=new HashMap<Integer,Object>();
			params.put(1,value);
			boolean is_ok=false;
			HashMap<String,String> user=new HashMap<String,String>();
			if(column.equals("username"))
				{ if(members.validUserName(value))
					{  is_ok=true;
					user=members.fields("uid,username,mobile,email").where("username=?").prepareRows(params);
					}
					else
					{res="{\"code\":-1,\"msg\":\"invalid username\"}";//用户名无效
					}
				}
				else if(column.equals("mobile"))
				{ if(valid().checkMobile(value,country))
					{is_ok=true;
					user=members.fields("uid,username,mobile,email").where("mobile=?").prepareRows(params);
					}
					else
					{ res="{\"code\":5,\"msg\":\"wrong mobile\"}";//手机号码格式不正确
					}
				}
				else if(column.equals("email"))
				{ if(valid().checkEmail(value))
					{
					user=members.fields("uid,username,mobile,email").where("email=?").prepareRows(params);
					is_ok=true;
					}
					else
					{res="{\"code\":6,\"msg\":\"wrong email\"}";//邮件格式不正确
					}
				}
				else
				{res="{\"code\":-3,\"msg\":\"invalid check\"}";
				}
		
			if(is_ok)
				{
				if(user!=null && !user.isEmpty() && null !=user.get("uid") && "".equals(user.get("uid"))==false)
				{res="{\"code\":1,\"msg\":\"success\",\"uid\":"+user.get("uid")+",\"username\":\""+user.get("username")+"\",\"user_name\":\""+user.get("username")+"\",\"mobile\":\""+user.get("mobile")+"\",\"email\":\""+user.get("email")+"\"}";
				}
					else
					{res="{\"code\":2,\"msg\":\""+column+" don't exists\"}";
					}
				}
			}
	   } else {
		   res = "{\"code\":-4,\"msg\":\"illegal\"}";//非法
	   }
	   echo(res);
	}
	
	public void drop() {
		String res="";
		if(valid) {
			String username=P("username");	
			HashMap<Integer,Object> params=new HashMap<Integer,Object>();
			params.put(1,username);
			int n=members.where("username=?").prepareDelete(params);
			if(n>0)
			{res="{\"code\":1,\"msg\":\"success\"}";//删除成功
			}
			else
			{res="{\"code\":-2,\"msg\":\"failed\"}";//删除失败
			}
		} else {
			res = "{\"code\":-4,\"msg\":\"illegal\"}";//非法
		}
	    echo(res);
	}

	private boolean verify(String src,String sign,String pubkey)
	{boolean res=false;
	  res=RsaVerifyMd5(md5(src),sign,pubkey);
	 return res;
	}

}